package com.ricky.web.api;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ricky.base.bean.ApiResult;
import com.ricky.base.bean.DbClient;
import com.ricky.base.bean.SshClient;
import com.ricky.base.util.Sm4Util;
import com.ricky.web.table.Server;
import com.ricky.web.util.SshUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;


/**
 * @author Ricky
 * @date 2020/11/30
 */
@Api(tags = "服务器配置接口")
@RestController
@RequestMapping("/server")
public class ServerController {
    @ApiOperation(value = "添加服务器")
    @ApiOperationSupport(ignoreParameters = {"server.id"})
    @PostMapping("/addServer")
    public ApiResult<Integer> addServer(@RequestBody Server server) throws Exception {
        int res;
        server.setId(UUID.randomUUID().toString());
        server.setPassword(Sm4Util.encrypt(server.getPassword(), "password"));
        try (SshClient sshClient = SshUtil.getSshClientByServer(server)) {
        }
        try (DbClient dbClient = new DbClient("database.db")) {
            res = dbClient.insert(server);
        }

        return ApiResult.success(res);
    }

    @ApiOperation(value = "修改服务器")
    @ApiOperationSupport(ignoreParameters = {})
    @PostMapping("/updateServer")
    public ApiResult<Integer> updateServer(@RequestBody Server server) throws Exception {
        int res;
        String pwd = server.getPassword();
        if (pwd.length() != 32) {
            server.setPassword(Sm4Util.encrypt(server.getPassword(), "password"));
        }
        try (SshClient sshClient = SshUtil.getSshClientByServer(server)) {
        }
        try (DbClient dbClient = new DbClient("database.db")) {
            res = dbClient.update(server);
        }

        return ApiResult.success(res);
    }

    @ApiOperation(value = "删除服务器")
    @ApiOperationSupport(includeParameters = {"server.id"})
    @PostMapping("/delServer")
    public ApiResult<Integer> delServer(@RequestBody Server server) throws Exception {
        int res;
        DbClient dbClient = new DbClient("database.db");
        res = dbClient.delete(server);
        dbClient.close();
        return ApiResult.success(res);
    }

    @ApiOperation(value = "获取所有服务器")
    @PostMapping("/getServerList")
    public ApiResult<List<Server>> getServerList() throws Exception {
        List<Server> res;
        DbClient dbClient = new DbClient("database.db");
        res = dbClient.getAll(Server.class);
        dbClient.close();
        return ApiResult.success(res);
    }
}
